<?php
require 'db.php';

$results = DB::query("select * from province");
DB::query("delete from city");

foreach ($results as $row) {

    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, "http://www.stats.gov.cn/tjsj/tjbz/tjyqhdmhcxhfdm/2018/{$row['code']}.html");
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    $data = curl_exec($curl);
    curl_close($curl);
    $data = mb_convert_encoding($data, 'UTF-8', 'GBK');

    // 裁头
    $offset = mb_strpos($data, 'citytr', 2000, 'GBK');
    $data = mb_substr($data, $offset, null, 'GBK');

    // 裁尾
    $offset = mb_strpos($data, '</table>', 0, 'GBK');
    $data = mb_substr($data, 0, $offset, 'GBK');

    preg_match_all('/\d{12}|[\x7f-\xff]+/', $data, $city);
    $city = $city[0];
    
    // 某个省份的城市
    $lists = array();
    for ($i = 0; $i < count($city); $i++) {
        $lists[] = array(
            'pid' => $row['code'],
            'code' => $city[$i++],
            'name' => $city[$i]
        );
    }
    DB::insert('city', $lists);
}

echo 'city插入成功';
